import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

/**定义保存用户购物车数据的仓库 */

const useCartStore = defineStore('cart', () => {

  // 用于保存购物车数据的数组
  const cart = ref([])

  // 计算总商品数量
  const totalAmount = computed(() => cart.value.reduce((sum, curr) => sum += curr.amount, 0))

  // 计算勾选商品的合计金额
  const totalMoney = computed(() => cart.value.reduce((sum, curr) => {
    if (curr.checked) {
      sum += curr.price_low * curr.amount * 100
    }
    return sum
  }, 0))

  // 计算是否全选
  const allChecked = computed(() => cart.value.every(curr => curr.checked))

  /**
   * 添加购物车商品
   */
  const addToCart = (item) => {
    // 判断购物车中是否已有当前选购商品
    const has = cart.value.find(curr => curr.id === item.id)
    if (has) {
      has.amount += item.amount
    } else {
      cart.value.push(item)
    }
  }

  /**
   * 修改购物车中商品数量
   */
  const modifyAmount = (id, amount) => {
    const has = cart.value.find(curr => curr.id === id)
    if (has) {
      has.amount = amount
    }
  }

  /**
   * 从购物车中移除保存的商品
   * @param id 
   */
  const removeFromCart = (id) => {
    cart.value = cart.value.filter(curr => curr.id !== id)
  }

  /**
   * 切换全选与取消
   * @param allChecked 选中状态
   */
  const toggleAllChecked = (allChecked) => {
    cart.value.forEach(curr => curr.checked = allChecked)
  }

    /**
   * 从购物车中移除保存的商品
   */
     const removeChenckedCart = () => {
      cart.value = cart.value.filter(curr => curr.checked === false)
    }
  return {
    cart,
    addToCart,
    modifyAmount,
    totalAmount,
    removeFromCart,
    totalMoney,
    allChecked,
    toggleAllChecked,
    removeChenckedCart,
  }
})

export default useCartStore
